// 全局选择责任人

import { useState } from "react";
import { ScrollView, View } from "@tarojs/components";
import PopupContainer from "./PopupContainer";
import { useCreation, useUpdateEffect } from "ahooks";

import ByTabs from "../ui/ByTabs";
import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import BySearchBar from "@/components/ui/BySearchBar";
import { ByPopupBottomEvent } from "@/components/ui/ByPopupBottom";

import {
  OptionMember,
  OptionProjectMember,
  OptionSuplier,
  OptionWorker,
} from "@/components/app/SelectOption";

import useList from "@/hooks/useList";
import ApiApp from "@/api/app";

import { Supplier, Worker, UserInfo } from "@/types/work";

const tabList = [
  {
    label: "项目成员",
    alias: "project",
    api: ApiApp.projectMemberList,
    key: "userId",
    textKey: "userName",
  },
  {
    label: "工人",
    alias: "worker",
    api: ApiApp.workerList,
    key: "workerId",
    textKey: "workerName",
  },
  {
    label: "ERP用户",
    alias: "erp",
    api: ApiApp.getUserList,
    key: "user_id",
    textKey: "userName",
  },
  {
    label: "供应商",
    alias: "supplier",
    api: ApiApp.supplierList,
    key: "supplyId",
    textKey: "supplyName",
  },
] as const;

export default ({
  type = ["worker", "erp", "supplier"],
  title,
  multiple,
  intentCustomerId,
  defaultSelected,

  onConfirm,
  onCancel,
}: ByPopupBottomEvent & {
  onConfirm?: (data: any, type: (typeof tabList)[number]["alias"]) => void;

  title?: string;
  multiple?: boolean;
  defaultSelected?: any[];
  intentCustomerId?: number;
  type?: Array<(typeof tabList)[number]["alias"]>;
}) => {
  // 获取配置的tab
  const renderTabs = useCreation(() => {
    if (type && type.length > 0) {
      return tabList.filter((item) => type?.includes(item.alias));
    } else {
      return tabList;
    }
  }, []);

  // 选中的数据
  const [selected, setSeleted] = useState<Array<Supplier & Worker & UserInfo>>(
    []
  );

  const handleSelected = (item, key) => {
    if (multiple) {
      const index = selected.findIndex((e) => item[key] === e[key]);
      if (index > -1) {
        selected.splice(index, 1);
      } else {
        selected.push(item);
      }

      setSeleted([...selected]);
    } else {
      setSeleted([item]);
    }
  };

  const checkedSelcted = (key, target) =>
    !!selected.find((e) => target[key] === e[key]);

  // 搜索关键字
  const [keyword, setKeyword] = useState<string>("");

  // 默认选中第一个
  const [active, setActive] = useState<number>(0);
  // 选中的tab配置内容
  const activeTab = renderTabs[active];

  const { loading, list, resetToFirst, nextPage } = useList<Supplier & Worker>(
    () => activeTab.api,
    { defaultParams: [{ pageSize: 100, intentCustomerId }] }
  );

  useUpdateEffect(() => {
    resetToFirst({ [activeTab.textKey]: keyword, intentCustomerId });
  }, [active, keyword]);

  const { alias, key } = activeTab;

  const NodeItem =
    alias === "project"
      ? OptionProjectMember
      : alias === "supplier"
        ? OptionSuplier
        : alias === "erp"
          ? OptionMember
          : OptionWorker;


  console.log("selected", selected);

  return (
    <PopupContainer title={title} onCancel={onCancel}>
      <View className="px-3">
        {alias !== "project" && (
          <BySearchBar
            circle
            height="66rpx"
            placeholder="输入名称搜索"
            onConfirm={setKeyword}
            onClear={() => setKeyword("")}
          />
        )}

        {renderTabs.length > 1 && (
          <ByTabs
            capsule
            active={active}
            className="my-2"
            tabs={renderTabs}
            onChange={setActive}
          />
        )}
      </View>

      <ScrollView
        scroll-y
        className="px-3 h-[60vh] sizing-border"
        onScrollToLower={() => nextPage()}
      >
        <ListView loading={loading} isEmpty={list.length === 0}>
          {list.map((item) => (
            <NodeItem
              border
              source={item as any}
              key={item[activeTab.key] + "_" + item.postId}
              checked={item[key] && checkedSelcted(key, item)}
              onClick={() => handleSelected(item, key)}
            />
          ))}
        </ListView>
      </ScrollView>

      <View className="border-t border-line-light safe-footer">
        <ByRow content="between" align="center" className="py-2 px-3">
          <ByCol span={"auto"} className="text-sm">
            {selected && (
              <ByText truncated>
                已选:
                {selected[0]?.supplyName ||
                  selected[0]?.user_name ||
                  selected[0]?.workerName ||
                  selected[0]?.userName}
                {selected.length > 1 && (
                  <ByText type="third">等{selected.length}项</ByText>
                )}
              </ByText>
            )}
          </ByCol>

          <ByCol span={"none"}>
            <ByButton
              onClick={() =>
                onConfirm?.(multiple ? selected : selected[0], alias as any)
              }
            >
              确定
            </ByButton>
          </ByCol>
        </ByRow>
      </View>
    </PopupContainer>
  );
};
